import {  RequestConfig } from "@umijs/max";//,AxiosResponse
import {message}from 'antd'
// 运行时配置
export async function getInitialState(): Promise<{ name: string }> {
  return { name: '@umijs/max' };
}

export const layout = () => {
  return {
    logo: 'https://img.alicdn.com/tfs/TB1YHEpwUT1gK0jSZFhXXaAtVXa-28-27.svg',
    menu: {
      locale: false,
    },
  };
};

type ResponseStatus= 200 | 199 | 401 | 404 | 500
interface ResponseType {
  status:ResponseStatus,
  data:any,
  message:string,
}

export const request: RequestConfig = {
  timeout: 1000, // 请求超时时间
  errorConfig: { // 错误处理配置
    errorHandler: (error: any) => {
      if(error.name==='monkey'){
        const status = error.info as Exclude<ResponseStatus, 200>;
        switch (status) {
          case 401:
          case 199:
          case 404:
          case 500:
            message.error(error.message);
            break;
          default:
            const _exhaustiveCheck: never = error.info;
            break;
        }
      }
      else if(error.response){
        message.error(`Response status:${error.response.status}`)
      }
      else if(error.request){
          message.error(`None response! Please retry`)
      }
      else{
        message.error(error.message)
      }
  }},
  requestInterceptors: [
   async (config: any) => {
      config.url = '/api' + config.url;
      config.headers = {
        'Content-Type': 'application/json',
        Authorization:sessionStorage.getItem('token'),
        ...(config.headers || {}),
      };
      await new Promise(resolve =>{setTimeout(resolve, 1000)});
      return config;
    },
  ],
  responseInterceptors: [
    (response) => {
      if (response.status === 200) {
        const { status, message } = response.data as ResponseType;
        if (status === 200) return response.data;
        const error = new Error(message);
        error.name = 'monkey';
        error.info = status;
        // error.cause = status;
        throw error;
      } else
        throw new Error(
          `staus:${response.status}/statusText${response.statusText}`,
        );
    },
  ]
}